package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.client.CourseDocClient;
import cn.itsource.hrm.config.RabbitMQConfig;
import cn.itsource.hrm.doc.CourseDoc;
import cn.itsource.hrm.domain.*;
import cn.itsource.hrm.dto.CourseDto;
import cn.itsource.hrm.enums.CourseGrade;
import cn.itsource.hrm.exception.GlobalException;
import cn.itsource.hrm.exception.ValidUtils;
import cn.itsource.hrm.holder.UserContextInfoHolder;
import cn.itsource.hrm.mapper.*;
import cn.itsource.hrm.query.CourseDocQuery;
import cn.itsource.hrm.query.CourseQuery;
import cn.itsource.hrm.service.ICourseService;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.PageList;
import cn.itsource.hrm.vo.UserContextInfo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2021-02-02
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseTypeMapper courseTypeMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseDetailMapper courseDetailMapper;
    @Autowired
    private CourseResourceMapper courseResourceMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Autowired
    private CourseDocClient courseDocClient;

    //由于关联三张表，增删改所以要做关联操作

    @Override
    public boolean deleteById(Serializable id) {
        //基本信息
        courseMapper.deleteById(id);
        //市场信息
        courseMarketMapper.deleteById(id);
        //详情信息
        courseDetailMapper.deleteById(id);
        //资源信息
        courseResourceMapper.removeByCourseId(id);
        return true;
    }


    //@TODO 自己做
    @Override
    public void update(CourseDto courseDto) {

    }

    @Override
    public void insert(CourseDto courseDto) {
        //返回自增id
        Course course = courseDto.getCourse();
        //1 处理等级
        Long gradeId = course.getGradeId();
        //校验
        CourseGrade grade = CourseGrade.GetGrade(gradeId.intValue());
        ValidUtils.assertNotNull(grade, "请选择合法等级！");
        //通过id获取对应gradeName并进行设置
        course.setGradeName(grade.getGradeName());

        //2 userId userName tenantId tenantName 这些信息都应该是当前登录用户信息和机构信息
        courseMapper.insert(course);
        CourseDetail courseDetail = courseDto.getCourseDetail();
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);
        CourseMarket courseMarket = courseDto.getCourseMarket();
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);
    }

    @Override
    public void onlineOrOffline(Long courseId, int flag) {
        //SecurityContext context = SecurityContextHolder.getContext();
        //Authentication authentication = context.getAuthentication();
        //String userContextInfoStr = (String) authentication.getPrincipal(); //Username-yaosang110
        //UserContextInfo userContextInfo = JSONObject.parseObject(userContextInfoStr, UserContextInfo.class);
        UserContextInfo userContextInfo = UserContextInfoHolder.getUserContextInfo();
        System.out.println(userContextInfo);
        //1 查询课程
        Course course = courseMapper.selectById(courseId);
        //2 状态判断：如果上线的话只能下线状态才能操作，依次类推
        Integer status = course.getStatus();
        if (flag==1){
            //上线
            ValidUtils.assertIntEqual(1, status.intValue(),
                    "该课程已经上线了，不能重复上线！");
            Map<String,Object> params = new HashMap<>();
            params.put("id", courseId);
            params.put("onlineTime", new Date());
            //3 修改数据库状态和对应时间
            courseMapper.online(params);//时间，id
            //4 保存数据到es-调用远程搜索服务（feign）
            CourseDoc courseDoc =course2courseDoc(course);
            AjaxResult ajaxResult = courseDocClient.addOrUpdateCourseDoc(courseDoc);
            ValidUtils.assertBoolean(ajaxResult.isSuccess(), ajaxResult.getMessage());

            //5 消息推送 邮件 短信 站内信
            publishMesage(course);


            //6 调用页面模块的接口完成页面静态化

        }else{
            //下线
            ValidUtils.assertIntEqual(0, status.intValue(),
                    "该课程已经下线了，不能重复下线！");
            //3 修改数据库状态和对应时间
            Map<String,Object> params = new HashMap<>();
            params.put("id", courseId);
            params.put("offlineTime", new Date());
            //3 修改数据库状态和对应时间
            courseMapper.offline(params);//时间，id
            //4 保存数据到es-调用远程搜索服务（feign）courseDoc
            AjaxResult ajaxResult = courseDocClient.deleteCourseDoc(courseId);
            ValidUtils.assertBoolean(ajaxResult.isSuccess(), ajaxResult.getMessage());

            //5 调用页面模块的接口删除静态页面
        }
    }

    @Override
    public PageList<CourseDoc> queryCourses(CourseDocQuery query) {
        return courseDocClient.queryPage(query);
    }

    private void publishMesage(Course course) {
        //邮件
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC,"message.email", course.getName());
        //短信
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC,"message.sms", course.getName());
        //站内信息
        //rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC,"message.system", course.getName());
    }

    //把一个课程转换为课程文档
    private CourseDoc course2courseDoc(Course course) {
        CourseDoc doc = new CourseDoc();
        //转换
        BeanUtils.copyProperties(course, doc);

        //类型名称转换
        Long courseTypeId = course.getCourseTypeId();
        CourseType courseType = courseTypeMapper.selectById(courseTypeId);
        doc.setCourseTypeName(courseType.getName());


        Long courseId = course.getId();
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        BeanUtils.copyProperties(courseMarket, doc);
        //不需要详情和resource，列表时不需要
        return doc;
    }
}
